package com.test.cordova.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @version V1.0
 * @desc AES 加密工具类
 */
public class AesUtil {

    /**
     * 加密
     *
     * @param sourceStr 源数据
     * @param key       密钥
     */
    public static String ecbEnc(String sourceStr, String key) {
        String rs = null;
        try {
            byte[] inBytes = sourceStr.getBytes();
            byte[] keyBytes = key.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// "算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(inBytes);
            rs = HexUtil.bytesToHex(encrypted).toUpperCase();
        } catch (Exception e) {
            String strExp = e.getMessage();
        }
        return rs;
    }

    /**
     * 解密
     *
     * @param hexStr 十六进制字符串
     * @param key    密钥
     */
    public static String ecbDec(String hexStr, String key) {
        String rs = null;
        try {
            byte[] outBytes = HexUtil.hexToBytes(hexStr);
            byte[] keyBytes = key.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// "算法/模式/补码方式"
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] decBytes = cipher.doFinal(outBytes);
            rs = new String(decBytes, "utf-8");
        } catch (Exception e) {
            String strExp = e.getMessage();
        }
        return rs;
    }

}
